package logic

import (
	"gitee.com/kristas/booting-go/framework/common/util/properties"
	"gitee.com/kristas/booting-go/gen_tool/booctl/creator"
	"gitee.com/kristas/booting-go/gen_tool/booctl/util"
	"strings"
)

var cmd util.GoCmd

func CreateAPIHandler(controllerName, group string) error {
	controller := &creator.ControllerFile{
		ControllerName: controllerName,
		Group:          group,
	}
	s := &creator.ScanFile{Path: "api"}
	defer cmd.FmtAll("api")
	return creator.NewBatchCreator(controller, s).Create()
}

func CreateServiceHandler(serviceName string) error {
	svc := &creator.ServiceFile{
		ServiceName: serviceName,
	}
	s := &creator.ScanFile{Path: "service"}
	err := creator.NewBatchCreator(svc, s).Create()
	if err != nil {
		return err
	}
	return GenEntry(false, "service")
}

func CreateFilterHandler(filterName, pattern string, order int) error {
	if pattern == "" {
		pattern = "/*"
	}
	filter := &creator.FilterFile{
		FilterName: filterName,
		Pattern:    pattern,
		Order:      order,
	}
	s := &creator.ScanFile{Path: "filter"}
	defer cmd.FmtAll("filter")
	return creator.NewBatchCreator(filter, s).Create()
}

func CreateRepositoryHandler(repoName, table, datasource string) error {
	err := UseGorm()
	if err != nil {
		return err
	}
	err = UseDatasource()
	if err != nil {
		return err
	}
	err = createRepository(repoName, table, datasource)
	if err != nil {
		return err
	}
	return GenEntry(false, "repository")
}

func createRepository(repoName, table, datasource string) error {
	r := &creator.RepositoryFile{
		RepoName:   repoName,
		Table:      table,
		DataSource: datasource,
	}
	s := &creator.ScanFile{Path: "repository"}
	return creator.NewBatchCreator(r, s).Create()
}

func CreateConfigHandler(env string, config []string) error {
	props := strings.Join(config, "\n")
	propMap := make(map[string]interface{})
	err := properties.Unmarshal([]byte(props), &propMap)
	if err != nil {
		return err
	}
	c := &creator.ConfigFile{
		Env:       env,
		Config:    propMap,
		Overwrite: true,
	}
	return c.Create()
}
